package com.example.tweetfeed;

import java.util.ArrayList;

import android.app.Activity;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;

public class MainActivity extends Activity{
	private TwitterBearerToken mToken = null;
	
//loading views
	private View mLoadingTweet = null;
	private ListView mTweetList = null;
	TweetAdapter mAdapter = null;

//orientation change data to save
	private ArrayList<Tweet> mTweetResult = null;
	private static final String STATE_RESULT_TWEET = "com.example.tweetfeed.STATE_RESULT_TWEET";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		loadContainers();
		handleIntent(getIntent());
		//prevent token to be destroyed
		saveDataFragment();
		if(savedInstanceState != null)
		{
			restoreState(savedInstanceState);
		}
	}
	
	private void loadContainers() {
		mLoadingTweet = findViewById(R.id.load_all);
		mTweetList = (ListView) findViewById(R.id.tweet_list);
		mAdapter = new TweetAdapter(this, new ArrayList<Tweet>());
		mTweetList.setAdapter(mAdapter);
	}
	
	private void saveDataFragment() {
		mToken = (TwitterBearerToken) getFragmentManager().findFragmentByTag("bearerToken");

        if (mToken == null) {
        	mToken = TwitterFetcher.getToken();
        	getFragmentManager().beginTransaction().add(mToken, "bearerToken").commit();
        }
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		registerReceiver(mReceiver, new IntentFilter(TwitterFetcher.TFRM_BROADCAST));
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(mReceiver);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
//Internet connection check
	protected boolean hasInternetConnection() {
	    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    return cm.getActiveNetworkInfo() != null && 
	    	   cm.getActiveNetworkInfo().isConnectedOrConnecting();
	}

//Action bar setup
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
	//search setup
		SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
		searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_search) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

//Search control
	@Override
	protected void onNewIntent(Intent intent) {
	    setIntent(intent);
	    handleIntent(intent);
	}

	private void handleIntent(Intent intent) {
	    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
	    //check connection first
	    	if(!hasInternetConnection()) {
	    		showErrorMessage(R.string.offline_text);
				return;
			}
	    //Search with query
	    	String query = intent.getStringExtra(SearchManager.QUERY);
	    	
	    //send queryString to twitterService
	    	if(mToken != null) {
	    		Intent twitQuery = new Intent(this, TwitterFetcher.class);
	    		twitQuery.putExtra(TwitterFetcher.QUERY, query);
	    		twitQuery.putExtra(TwitterFetcher.QUERY_TKN, mToken.getValue());
	    		startService(twitQuery);
	    		
	    	//loading UI
	    		updateList(null);
	    		mLoadingTweet.setVisibility(View.VISIBLE);
	    	}
	    }
	}
//BroadcastReceiver
	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			mLoadingTweet.setVisibility(View.GONE);
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				boolean error = bundle.getBoolean(TwitterFetcher.RESULT_ERROR);
				if(!error) {
					mTweetResult = bundle.getParcelableArrayList(TwitterFetcher.RESULT_TWEET);
					updateList(mTweetResult);
				}
				else {
					showErrorMessage( R.string.search_error );
					return;
				}
			}
		}
	};
	
//Orientation change handlers
	@Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
    	super.onSaveInstanceState(savedInstanceState);
    	if(mTweetResult != null) {
    		savedInstanceState.putParcelableArrayList(STATE_RESULT_TWEET, mTweetResult);
    	}
    }
    
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        restoreState(savedInstanceState);
    }
    
    private void restoreState(Bundle savedInstanceState) {
    	if(savedInstanceState.containsKey(STATE_RESULT_TWEET)) {
    		mTweetResult = savedInstanceState.getParcelableArrayList(STATE_RESULT_TWEET);
    		updateList(mTweetResult);
    	}
    }
	
//error handling
	private void showErrorMessage(int alertid) {
		Toast.makeText(this, alertid, Toast.LENGTH_SHORT).show();
	}
	
//loading list
	private void updateList(ArrayList<Tweet> results) {
		boolean loading = results == null;
		mLoadingTweet.setVisibility(loading?View.VISIBLE:View.GONE);
		mTweetList.setVisibility(loading?View.GONE:View.VISIBLE);
		mAdapter.clear();
		if(!loading) {
			mAdapter.addAll(results);
		}
	}
}
